package com.xinqi.modules.homework.homework.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.base.response.R;
import com.xinqi.common.core.utils.MessageUtils;
import com.xinqi.common.mybatis.data.service.impl.BaseServiceImpl;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.course.clazz.client.ClassStudentClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.homework.homework.convert.CourseHomeworkRecordConvert;
import com.xinqi.modules.homework.homework.domain.CourseHomeworkEntity;
import com.xinqi.modules.homework.homework.domain.CourseHomeworkRecordEntity;
import com.xinqi.modules.homework.homework.dto.req.*;
import com.xinqi.modules.homework.homework.dto.rsp.CourseHomeworkFileResultDTO;
import com.xinqi.modules.homework.homework.dto.rsp.CourseHomeworkRecordResultDTO;
import com.xinqi.modules.homework.homework.dto.rsp.CourseHomeworkStudentHistoryResultDTO;
import com.xinqi.modules.homework.homework.dto.rsp.CourseHomeworkStudentInfoResultDTO;
import com.xinqi.modules.homework.homework.mapper.CourseHomeworkMapper;
import com.xinqi.modules.homework.homework.mapper.CourseHomeworkRecordMapper;
import com.xinqi.modules.homework.homework.mapper.CourseHomeworkStudentLogMapper;
import com.xinqi.modules.homework.homework.service.CourseHomeworkFileService;
import com.xinqi.modules.homework.homework.service.CourseHomeworkRecordService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 作业学生提交记录表服务层实现
 *
 * @author: system
 * @date: 2023/03/08
 */
@Service("courseHomeworkRecordService")
@RequiredArgsConstructor
public class CourseHomeworkRecordServiceImpl extends BaseServiceImpl<CourseHomeworkRecordMapper, CourseHomeworkRecordEntity> implements CourseHomeworkRecordService {

    private final CourseHomeworkRecordConvert courseHomeworkRecordConvert;
    private final CourseHomeworkStudentLogMapper courseHomeworkStudentLogMapper;
    private final CourseHomeworkFileService courseHomeworkFileService;

    private final CourseHomeworkMapper homeworkMapper;

    private final ClassStudentClient classStudentClient;

    /**
     * 分页查询 作业学生提交记录表数据
     */
    @Override
    @DS("slaver")
    public PageInfo<CourseHomeworkRecordResultDTO> page(Param pageable, CourseHomeworkRecordQueryDTO query) {
        return this.baseMapper.selectDtoPageInfo(Pages.page(pageable), wrapper(query), courseHomeworkRecordConvert::convert);
    }

    /**
     * 查询 作业学生提交记录表数据
     */
    @Override
    public List<CourseHomeworkRecordResultDTO> find(CourseHomeworkRecordQueryDTO query) {
        List<CourseHomeworkRecordResultDTO> list = this.baseMapper.selectDtoList(wrapper(query), courseHomeworkRecordConvert::convert);
        list.forEach(item -> {
            CourseHomeworkFileQueryDTO fileQueryDTO = new CourseHomeworkFileQueryDTO();
            fileQueryDTO.setRecordId(item.getId());
            item.setList(courseHomeworkFileService.find(fileQueryDTO));
        });
        return list;
    }

    /**
     * 查询 作业学生提交记录根据作业ID、作业轮数和学生ID
     */
    @Override
    public CourseHomeworkRecordResultDTO findByParam(CourseHomeworkRecordQueryDTO query) {
        List<CourseHomeworkRecordResultDTO> list = this.baseMapper.selectDtoList(wrapper(query), courseHomeworkRecordConvert::convert);
        CommonErrors.NOT_IMPLEMENTED.check(list.size() == 0 || list.size() == 1, "查询异常出现多个");
        if (list.size() == 0) {
            return null;
        } else {
            CourseHomeworkRecordResultDTO recordResultDTO = list.get(0);
            CourseHomeworkFileQueryDTO fileQueryDTO = new CourseHomeworkFileQueryDTO();
            fileQueryDTO.setRecordId(recordResultDTO.getId());
            recordResultDTO.setList(courseHomeworkFileService.find(fileQueryDTO));
            return recordResultDTO;
        }
    }

    /**
     * 查询 作业学生提交记录表数据带作业文件列表
     */
    @Override
    public CourseHomeworkStudentHistoryResultDTO findAll(CourseHomeworkStudentDetailDTO query) {

        CommonErrors.BAD_REQUEST.check(query.getContentId() != null, "作业ID不能为空");
        CommonErrors.BAD_REQUEST.check(query.getTimes() != null, "作业轮数不能为空");
        CommonErrors.BAD_REQUEST.check(query.getStudentId() != null, "学生ID不能为空");

        // 判断作业是否被删除
        CourseHomeworkEntity entity = homeworkMapper.selectById(query.getContentId());
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(entity), MessageUtils.message("course.homework.id.not.exit"));

        // 获取真实用户信息
        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(entity.getClassId(), query.getStudentId()));
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(mainStudent), MessageUtils.message("course.common.student.not.exit"));
        query.setStudentId(mainStudent.getStudentId());

        CourseHomeworkStudentHistoryResultDTO resultDTO = new CourseHomeworkStudentHistoryResultDTO();
        CourseHomeworkStudentLogQueryDTO studentLogQueryDTO = new CourseHomeworkStudentLogQueryDTO();
        studentLogQueryDTO.setContentId(query.getContentId());
        studentLogQueryDTO.setTimes(query.getTimes());
        studentLogQueryDTO.setStudentId(query.getStudentId());
        List<CourseHomeworkStudentInfoResultDTO> studentInfoList = courseHomeworkStudentLogMapper.homeworkStudentInfoList(studentLogQueryDTO);
        if (CollectionUtils.isNotEmpty(studentInfoList)) {
            resultDTO.setStudentInfo(studentInfoList.get(0));
        }
        CourseHomeworkRecordQueryDTO recordQueryDTO = new CourseHomeworkRecordQueryDTO();
        recordQueryDTO.setContentId(query.getContentId());
        recordQueryDTO.setTimes(query.getTimes());
        recordQueryDTO.setStudentId(query.getStudentId());
        List<CourseHomeworkRecordResultDTO> list = this.baseMapper.findList(recordQueryDTO);
        list.forEach(item -> {
            CourseHomeworkFileQueryDTO fileQueryDTO = new CourseHomeworkFileQueryDTO();
            fileQueryDTO.setRecordId(item.getId());
            List<CourseHomeworkFileResultDTO> fileList = courseHomeworkFileService.find(fileQueryDTO);
            item.setList(fileList);
        });
        resultDTO.setList(list);
        return resultDTO;
    }

    private LambdaQueryWrapper<CourseHomeworkRecordEntity> wrapper(CourseHomeworkRecordQueryDTO query) {
        LambdaQueryWrapper<CourseHomeworkRecordEntity> wrapper = Queries.lambda();
        wrapper.orderByDesc(CourseHomeworkRecordEntity::getCreateTime);
        if (query.getId() != null) {
            Queries.accept(query.getId(), v -> wrapper.eq(CourseHomeworkRecordEntity::getId, v));
        }
        if (Objects.nonNull(query.getContentId())) {
            Queries.accept(query.getContentId(), v -> wrapper.eq(CourseHomeworkRecordEntity::getContentId, v));
        }
        if (Objects.nonNull(query.getTimes())) {
            Queries.accept(query.getTimes(), v -> wrapper.eq(CourseHomeworkRecordEntity::getTimes, v));
        }
        if (Objects.nonNull(query.getStudentId())) {
            Queries.accept(query.getStudentId(), v -> wrapper.eq(CourseHomeworkRecordEntity::getStudentId, v));
        }
        if (Objects.nonNull(query.getInProgress())) {
            Queries.accept(query.getInProgress(), v -> wrapper.eq(CourseHomeworkRecordEntity::getInProgerss, v));
        }
        return wrapper;
    }

    /**
     * 根据id查询 作业学生提交记录表数据
     */
    @Override
    public CourseHomeworkRecordResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), MessageUtils.message("course.homework.id.not.blank"));
        CourseHomeworkRecordResultDTO recordResultDTO = this.baseMapper.selectDtoById(id, courseHomeworkRecordConvert::convert);
        //查询学生提交作业文件内容
        CourseHomeworkFileQueryDTO fileQueryDTO = new CourseHomeworkFileQueryDTO();
        fileQueryDTO.setRecordId(recordResultDTO.getId());
        List<CourseHomeworkFileResultDTO> fileList = courseHomeworkFileService.find(fileQueryDTO);
        recordResultDTO.setList(fileList);
        return recordResultDTO;
    }


    /**
     * 根据id修改 作业学生提交记录表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(CourseHomeworkRecordUpdateDTO dto) {
        CourseHomeworkRecordEntity old = Optional.ofNullable(this.getById(dto.getId()))
                .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException(MessageUtils.message("data.does.not.exist")));
        CourseHomeworkRecordEntity entity = courseHomeworkRecordConvert.update(dto);
        return this.updateById(entity);
    }

    @Override
    public Boolean updataByParam(CourseHomeworkRecordUpdateDTO dto) {
        CourseHomeworkRecordEntity entity = new CourseHomeworkRecordEntity();
        if (dto.getInProgress() != null) {
            entity.setInProgerss(2);
        }
        entity.setIsRepulse(1);
        LambdaQueryWrapper<CourseHomeworkRecordEntity> wrapper = new LambdaQueryWrapper();
        wrapper.eq(CourseHomeworkRecordEntity::getContentId, dto.getContentId());
        wrapper.eq(CourseHomeworkRecordEntity::getTimes, dto.getTimes());
        wrapper.eq(CourseHomeworkRecordEntity::getStudentId, dto.getStudentId());
        return this.update(entity, wrapper);
    }

    /*历史评语*/
    @Override
    public List<String> findHistoryComment(CourseHomeworkRecordQueryDTO dto) {
        return this.baseMapper.findHistoryComment(dto);
    }

    @Override
    public CourseHomeworkRecordEntity getLastRecord(Long classId, Long studentId, Long contentId) {
        LambdaQueryWrapper<CourseHomeworkRecordEntity> wrapper = new LambdaQueryWrapper();
        wrapper.eq(CourseHomeworkRecordEntity::getContentId, contentId);
        wrapper.eq(CourseHomeworkRecordEntity::getStudentId, studentId);
        wrapper.orderByDesc(CourseHomeworkRecordEntity::getCreateTime);
        wrapper.last("limit  1");
        return this.baseMapper.selectOne(wrapper);
    }


}
